import { NextApiRequest, NextApiResponse } from 'next'
import {withIronSessionApiRoute} from 'iron-session/next'
import { Cookie } from 'next-cookie'
import { setCookie } from 'utils/index'
import {prepareConnection} from 'db/index'
import { User, UserAuth } from 'db/entity/index'
import {ironOptions} from 'config/index'
import { ISession} from 'pages/api/index'

export default withIronSessionApiRoute(login,ironOptions)

async function login(req: NextApiRequest, res: NextApiResponse) {

    const sesssion: ISession = req.session
    const cookies = Cookie.fromApiRoute(req,res)
    // 连接数据库
    const db = await prepareConnection()
    const userAuthRepo = db.getRepository(UserAuth)
    // 1. 获取请求参数
    const { phone = '', verify = '',identity_type='phone'} = req.body
    if(String(sesssion.verifyCode) === String(verify)) {
        // 验证码正确 在user_auth表中查找 identity_type 是否有记录
        const userAuth = await userAuthRepo.findOne(
            {
                identity_type,
                identifier: phone,
            },{
                relations: ['user']
        })

        if(userAuth) {
            // 存在则更新
            const user = userAuth.user
            const { id,nickname,avatar } = user
            sesssion.userId = id
            sesssion.nickname = nickname
            sesssion.avatar = avatar

            await sesssion.save()

            setCookie(cookies, {id,nickname,avatar})

            res?.status(200).json({code:0,msg:'登录成功',data: {userId:id,nickname,avatar}})
       
        } else {
            // 不存在则新建
            const user = new User()
            user.nickname = `用户_${Math.floor(Math.random()*10000)}`
            user.avatar = '/images/avatar.png'
            user.job = '前端工程师'
            user.introduce = '我是前端工程师'

            const userAuth = new UserAuth()
            userAuth.identifier = phone
            userAuth.identity_type = identity_type
            userAuth.credential = sesssion.verifyCode
            userAuth.user = user

            const resUserAuth = await userAuthRepo.save(userAuth)
            const {user:{id,nickname,avatar}} = resUserAuth
            sesssion.userId = id
            sesssion.nickname = nickname
            sesssion.avatar = avatar

            await sesssion.save()
            setCookie(cookies, {id,nickname,avatar})
            res?.status(200).json({code:0,msg:'登录成功',data: {userId:id,nickname,avatar}})
            // 4.12
           
        }
    }else{
        res?.status(200).json({code:-1,msg:'验证码错误'})
    }
}